<?php

namespace app\index\controller;

use think\Controller;
use think\Validate;
use app\index\model\User as UserModel;
use app\index\model\Group as GroupModel;

class User extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 管理首页
     */
    public function index()
    {
        $users  = UserModel::getGrouper();
        $groups = GroupModel::all();

        return view('index', compact('users', 'groups'));
    }

    /**
     * 处理新增请求
     */
    public function save()
    {
        $validate = new Validate([
            'username' => 'require|max:16',
            'password' => 'require|max:16',
            'group_id' => 'require',
        ]);
        $data = input('post.');
        if (! $validate->check($data)) {
            $this->error($validate->getError());
            return ;
        }
        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);

        UserModel::clearGroup($data['group_id']);
        $user = new UserModel($data);
        $user->allowField(true)->save();
        $this->success('保存成功');
    }

    public function update()
    {
        $data = input('post.');
        if (empty($data['password'])) {
            unset($data['password']);
        } elseif (strlen($data['password']) < 6) {
            $this->error('密码至少6位');
            return ;
        } else {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        UserModel::clearGroup($data['group_id']);
        $user = new UserModel;
        $user->allowField(true)->save($data, ['id' => $data['id']]);

        $this->success('修改成功');
    }
}
